package LearnDataStructure.b_散列结构;

/**
 * @version: 1.0
 * @Author: wuqiu
 * @date: 2023-07-17 20:36
 * @description: LeetcodeLearnAlgorithm -> LearnDataStructure.b_散列结构
 */
public class MyHashFunctions {
    /*
    取余法
    对素数取余
     */
    public static int hashFunction1(Object source, int prime) {
        return source.hashCode() % prime;
    }

    /*
    加法
    遍历source的元素并叠加hashcode
    再取余素数
     */
    public static int hashFunction2(Object source, int prime) {
        String sourceStr = source.toString();
        int result = 0;
        int i = 0;
        while (i < sourceStr.length()) {
            result += sourceStr.charAt(i);
            i++;
        }
        return result % prime;
    }

    /*
    位运算:异或
    在“加法”上更加打乱
     */
    public static int hashFunction3(Object source, int prime) {
        String sourceStr = source.toString();
        int result = sourceStr.length();
        int i = 0;
        while (i < sourceStr.length()) {
            result = (result << 4) ^ (result >> 28) ^ sourceStr.charAt(i);
            i++;
        }
        return result % prime;
    }

    /*
    乘法
    遍历元素，在“加法”上同时进行偏移量操作
    seed偏移量
     */
    public static long hashFunction4(Object source, int prime) {
        String sourceStr = source.toString();
        long result = 0;
        long seed = 37;//偏移量，素数
        for (int i = 0; i < sourceStr.length(); i++) {
            result = seed * result + sourceStr.charAt(i);
        }
        return result % prime;
    }
}
